package alkaid.oss.local.domain;

import java.io.File;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;

import org.hibernate.annotations.CreationTimestamp;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import alkaid.oss.common.util.SnowflakeUtil;
import lombok.Data;
import lombok.ToString.Exclude;

/**
 * 文件元数据
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Data
@Entity(name = "oss_file_metadata")
@EntityListeners({ AuditingEntityListener.class })
public class FileMetadata {
    private final static String PATH_SEP = "/";

    @Id
    @Column(updatable = false, nullable = false, unique = true)
    private Long id;

    @Exclude
    @Version
    @Column(nullable = false)
    private Integer version;

    @Exclude
    @CreatedBy
    @Column(updatable = false)
    private String createBy;

    @Exclude
    @CreationTimestamp
    @Column(updatable = false)
    private Date createTime;

    /** 名称 */
    @Column(nullable = false)
    @Exclude
    private String name;

    /** 文件路径 */
    @Exclude
    @Column(updatable = false, nullable = false)
    private String path;

    /** 类型 */
    @Exclude
    private String contentType;

    /** 大小，字节 */
    @Exclude
    private Long size;

    public FileMetadata() {
    }

    public FileMetadata(String name, String path) {
        this.name = name;
        this.path = path;
    }

    public FileMetadata(String name, String path, String contentType, long size) {
        this.name = name;
        this.path = path;
        this.contentType = contentType;
        this.size = size;
    }

    @PrePersist
    @PreUpdate
    public void prePersist() {
        if (id == null) {
            id = SnowflakeUtil.INSTANCE.nextId();
        }
        if (path != null) {
            path.replace(File.separator, PATH_SEP);
        }
    }

    public boolean isNew() {
        return id == null;
    }

    public void copy(FileMetadata source) {
        BeanUtils.copyProperties(source, this, "id,path".split(","));
    }

    public String toRealPath() {
        if (path != null) {
            return path.replace(PATH_SEP, File.separator);
        }

        return null;
    }
}
